import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class Marble extends Thread {
    Table table = null;
    int x, y, xdir, ydir;

    public Marble(Table _table, int _x, int _y, int _xdir, int _ydir) {
        table = _table;
        x = _x;
        y = _y;
        xdir = _xdir;
        ydir = _ydir;
    }

    public void run() {
        while(true) {
            if ((x > (table.getSize().width) - 25) || (x < 0))
                xdir *= (-1);
            if ((y > (table.getSize().width) - 25) || (y < 0))
                ydir *= (-1);

            x += xdir;
            y += ydir;

            try {
                sleep(30);
            }
            catch(InterruptedException e) {
                System.out.println("Thread interrupted");
            }

            table.repaint();
        }
    }

    public void draw(Graphics g) {
        g.setColor(Color.black);
        g.fillOval(x, y, 30, 30);
        g.setColor(Color.white);
        g.fillOval(x + 5,  y + 5,  8,  6);
    }
}

class Table extends JFrame implements ActionListener {
    JButton start = new JButton("开始");
    Marble[] marbles = new Marble[5];
    int v = 2;
    public Table() {
        super("弹子台球");
        setSize(300, 300);
        setBackground(Color.cyan);
        setVisible(true);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(start);
        start.addActionListener(this);
        validate();
    }

    public void actionPerformed(ActionEvent ae) {
        for (int i = 0; i < marbles.length; i++) {
            int xdir = i * (1- i * (int)Math.round(Math.random())) + v;
            int ydir = i * (1- i * (int)Math.round(Math.random())) + v;
            int x = (int)(getSize().width * Math.random());
            int y = (int)(getSize().height * Math.random());

            marbles[i] = new Marble(this, x, y, xdir, ydir);
            marbles[i].start();
        }
    }

    public void paint(Graphics g) {
        super.paint(g);

        for (int i = 0; i < marbles.length; i++) {
            if (marbles[i] != null)
                marbles[i].draw(g);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Table table = new Table();
    }
}